import axios from 'axios'
import { baseUrl, ERR_OK, ERR_UNLOGIN } from './config'
import router from 'src/router'
const headUrl = baseUrl + '/api/order'

export function orderListApi () {
  const url = headUrl + '/list'
  return axios.get(url).then((res) => {
    if (res.data.errno === ERR_OK) {
      return Promise.resolve(res.data.data)
    }
    return Promise.reject(res.data.message)
  })
}

export function orderDetailApi (id) {
  const url = headUrl + '/detail'
  const data = {
    id
  }
  return axios.get(url, {
    params: data
  }).then((res) => {
    if (res.data.errno === ERR_OK) {
      return Promise.resolve(res.data.data)
    }
    return Promise.reject(res.data.message)
  })
}

export function orderCreateApi (data) {
  const url = headUrl + '/create'
  return axios.post(url, data).then((res) => {
    if (res.data.errno === ERR_OK) {
      return Promise.resolve(res.data.data)
    }
    return Promise.reject(res.data.message)
  })
}

export function orderDeleteApi (order) {
  const url = headUrl + '/delete'
  const data = {
    order
  }
  return axios.post(url, data).then((res) => {
    if (res.data.errno === ERR_OK) {
      return Promise.resolve(res.data.data)
    }
    return Promise.reject(res.data.message)
  })
}

export function setOrderStateApi (order, state) {
  const url = headUrl + '/updateState'
  const data = {
    order,
    state
  }
  return axios.post(url, data).then((res) => {
    if (res.data.errno === ERR_OK) {
      return Promise.resolve(res.data.data)
    }
    return Promise.reject(res.data.message)
  })
}

export function watchReceiverApi (orderId) {
  const url = headUrl + '/watchReceiver'
  const data = { orderId }
  return axios.post(url, data).then((res) => {
    if (res.data.errno === ERR_OK) {
      return Promise.resolve(res.data.data)
    }
    return Promise.reject(res.data.message)
  })
}
export function closeWRApi (orderId) {
  const url = headUrl + '/closeWR'
  const data = { orderId }
  return axios.post(url, data).then((res) => {
    if (res.data.errno === ERR_OK) {
      return Promise.resolve(res.data.data)
    }
    return Promise.reject(res.data.message)
  })
}

export function watchListApi () {
  const url = headUrl + '/watchList'
  return axios.post(url).then((res) => {
    if (res.data.errno === ERR_OK) {
      return Promise.resolve(res.data.data)
    }
    return Promise.reject(res.data.message)
  }).catch(error => {
    if (error.response && error.response.status === 504) {
      return Promise.resolve('timeout')
    }
    return Promise.reject(error)
  })
}

axios.interceptors.response.use(async (response) => {
  if (response.data.errno === ERR_UNLOGIN) {
    await router.replace({
      path: '/login'
    })
  }
  return response
})
